package jwei.apps.views;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;

import jwei.apps.R;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Movie;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.widget.ImageView;

public class AnimatedGifImageView extends ImageView {

    // default
    private int loader = 3;

    private InputStream is;

    private Movie mMovie;

    private long mMovieStart;

    // Set to false to use decodeByteArray
    private static final boolean DECODE_STREAM = false;

    public AnimatedGifImageView(Context context) {
        super(context);
        switch (loader) {
            case 1:
                is = context.getResources().openRawResource(R.drawable.loader);
                break;
            case 2:
                is = context.getResources().openRawResource(R.drawable.loader2);
                break;
            case 3:
                is = context.getResources().openRawResource(R.drawable.loader3);
                break;
        }

        if (DECODE_STREAM) {
            mMovie = Movie.decodeStream(is);
        } else {
            byte[] array = streamToBytes(is);
            mMovie = Movie.decodeByteArray(array, 0, array.length);
        }
    }

    // This constructor is used by LayoutInflater
    public AnimatedGifImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        new AnimatedGifImageView(context);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        Paint p = new Paint();
        p.setAntiAlias(true);

        long now = android.os.SystemClock.uptimeMillis();
        if (mMovieStart == 0) { // first time
            mMovieStart = now;
        }
        if (mMovie != null) {
            int dur = mMovie.duration();
            if (dur == 0) {
                dur = 1000;
            }
            int relTime = (int) ((now - mMovieStart) % dur);
            mMovie.setTime(relTime);
            mMovie.draw(canvas, getWidth() - mMovie.width(), getHeight() - mMovie.height());
            invalidate();
        } else {
            System.out.println("MOVIE WAS NULL");
        }
    }

    private static byte[] streamToBytes(InputStream is) {
        ByteArrayOutputStream os = new ByteArrayOutputStream(1024);
        byte[] buffer = new byte[1024];
        int len;
        try {
            while ((len = is.read(buffer)) >= 0) {
                os.write(buffer, 0, len);
            }
        } catch (java.io.IOException e) {
        }
        return os.toByteArray();
    }

    public void setLoader(int loader) {
        this.loader = loader;
        refreshDrawableState();
    }

}
